/*
* @Author: Adolphus.Yao
* @Date:   2019-08-29 15:32:03
* @Last Modified by:   Adolphus.Yao
* @Last Modified time: 2019-09-09 20:43:35
*/
package controllers

import (
    "fmt"
    "errors"
    "fulnero.com/iris/mvc/datamodels"
    "fulnero.com/iris/mvc/services"
    "github.com/kataras/iris"
    "github.com/kataras/iris/sessions"
)

type Test struct {
    Name string
    Psw string
}

type MovieController struct {
    Service services.MovieService
    Session *sessions.Session
}

func (mc *MovieController) BeginRequest(ctx iris.Context) {
    //var request map[string]interface{}
    //ctx.ReadJSON(request)
    body, _ := ctx.GetBody()
    bodyStr := string(body)
    fmt.Println("beginRequest")
    fmt.Println("request:", bodyStr)
    fmt.Println("bodyStr1:", mc.Session.GetStringDefault("bodyStr1", ""))
    mc.Session.Set("bodyStr", bodyStr)
}

func (mc *MovieController) EndRequest(ctx iris.Context) {
    ctx.ResponseWriter().Write([]byte("test"))
    ctx.ResponseWriter().Flush()
    fmt.Println("bodyStr:", mc.Session.GetString("bodyStr"))
    mc.Session.Set("bodyStr1", "bodyStr")
    fmt.Println("EndRequest")
}

func (mc *MovieController) PostTest(ctx iris.Context) string {
    fmt.Println("Test ....")
    var t Test
    if err := ctx.ReadJSON(&t); err != nil {
        fmt.Println("Test ....23323")
        ctx.StatusCode(iris.StatusBadRequest)
        ctx.WriteString(err.Error())
        return "ee"
    }
    fmt.Println("Test ....111")
    fmt.Println("t:", t)
    fmt.Println("Test ....222")
    fmt.Println("bodyStr:", mc.Session.GetString("bodyStr"))
    return "testssssssss"
}

func (c *MovieController) Get() (results []datamodels.Dao) {
    return c.Service.GetAll()
}

func (c *MovieController) GetBy(id int64) (movie datamodels.Dao, found bool) {
    return c.Service.GetByID(id)
}

func (c *MovieController) PutBy(ctx iris.Context, id int64) (datamodels.Dao, error) {
    file, info, err := ctx.FormFile("poster")
    if nil != err {
        return datamodels.Movie{}, errors.New("failed due form file 'poster' missing")
    }
    file.Close()
    poster := info.Filename
    genre := ctx.FormValue("genre")
    return c.Service.UpdatePosterAndGenreByID(id, poster, genre)
}

func (c *MovieController) DeleteBy(id int64) interface{} {
    wasDel := c.Service.DeleteByID(id)
    if wasDel {
        return iris.Map{"deleted": id}
    }
    return iris.StatusBadRequest
}